﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using Button = Ext.Net.Button;
using Component = Ext.Net.Component;
using Container = Ext.Net.Container;
using Label = Ext.Net.Label;
using LinkButton = Ext.Net.LinkButton;
using Menu = Ext.Net.Menu;
using MenuItem = Ext.Net.MenuItem;
using Panel = Ext.Net.Panel;

namespace KamLib.Controls
{

    public class MonitorControl : ButtonGroup, INamingContainer
    {

        [DefaultValue(typeof(Unit), "100")]
        public override Unit Height { get { return 100; } }
        [DefaultValue(typeof(Unit), "210")]
        public override Unit Width { get { return 210; } }

        protected Container cntMain;
        protected SplitButton cmdMain;
        protected MenuItem miInterval;
        protected CheckMenuItem miRI5;
        protected CheckMenuItem miRI15;
        protected CheckMenuItem miRI30;
        protected CheckMenuItem miRI60;
        protected CheckMenuItem miRI120;
        protected CheckMenuItem miRI300;
        protected CheckMenuItem miRI600;
        protected Button cmdRefresh;
        protected Button cmdRun;
        protected Button cmdStop;
        protected Label ErrorLink;
        protected TaskManager TM;

        protected override void CreateChildControls()
        {
            if (ChildControlsCreated) return;
            ChildControlsCreated = true;

            Plugins.Add(new MouseDistanceSensor { MinOpacity = 0.3m });

            Title = "Monitoring";
            Cls = "x-composite-btn1";
            Layout = "VBox";
            LayoutConfig.Add(new VBoxLayoutConfig { Align = VBoxAlign.Stretch });

            //Plugins.Add(new MouseDistanceSensor { MinOpacity = 0.25m });

            #region cmdMain

            cmdMain = new SplitButton
            {
                ID = "cmdMain",
                ToolTip = "Toggle Monitoring changes",
                IconCls = "x-btn-scale-64 icon-monitoring-64",
                //ArrowAlign = ArrowAlign.Bottom,
                OnClientClick = "KamLib.toggleButtons(#{cmdRun}, #{cmdStop});",
                Menu =
                {
                    new Menu
                    {
                        Items =
                        {
                            (miInterval = new MenuItem
                            {
                                ID = "miInterval",
                                Text = "Monitoring Interval",
                                Menu =
                                {
                                    new Menu
                                    {
                                        Listeners =
                                        {
                                            ItemClick = { Handler ="#{TM}.getTask('mnt').interval = [5, 15, 30, 60, 120, 300, 600][this.items.indexOf(menuItem)] * 1000;"}
                                        },
                                        Items =
                                        {
                                            (miRI5 = new CheckMenuItem
                                            {
                                                ID = "miRI5",
                                                Group = "ri",
                                                Text = "5 seconds",
                                                CommandName = "5"
                                            }),
                                            (miRI15 = new CheckMenuItem
                                            {
                                                ID = "miRI15",
                                                Group = "ri",
                                                Text = "15 seconds",
                                                CommandName = "15"
                                            }),
                                            (miRI30 = new CheckMenuItem
                                            {
                                                ID = "miRI30",
                                                Group = "ri",
                                                Text = "30 seconds",
                                                CommandName = "30"
                                            }),
                                            (miRI60 = new CheckMenuItem
                                            {
                                                ID = "miRI60",
                                                Group = "ri",
                                                Text = "1 minute",
                                                CommandName = "60"
                                            }),
                                            (miRI120 = new CheckMenuItem
                                            {
                                                ID = "miRI120",
                                                Group = "ri",
                                                Text = "2 minutes",
                                                CommandName = "120"
                                            }),
                                            (miRI300 = new CheckMenuItem
                                            {
                                                ID = "miRI300",
                                                Group = "ri",
                                                Text = "5 minutes",
                                                CommandName = "300"
                                            }),
                                            (miRI600 = new CheckMenuItem
                                            {
                                                ID = "miRI600",
                                                Group = "ri",
                                                Text = "10 minutes",
                                                CommandName = "600"
                                            }),
                                        }
                                    }
                                }
                            })
                        }
                    }
                }
            };

            #endregion

            var ctrlBar = new Toolbar
            {
                Layout = "HBox",
                Flex = 1,
                Height = 48,
                Flat = true,
                Margins = "0 0 0 2px",
                Items =
                {
                    (cmdRefresh = new Button
                    {
                        ID = "cmdRefresh",
                        ToolTip = "Refresh",
                        Cls = "x-btn-toggle",
                        IconCls = "icon-refresh-24",
                        Flex = 1,
                        Scale = ButtonScale.Medium,
                    }),
                    (cmdRun = new Button
                    {
                        ID = "cmdRun",
                        ToolTip = "Run monitoring now",
                        Cls = "x-btn-toggle",
                        IconCls = "icon-run2-24",
                        Flex = 1,
                        Scale = ButtonScale.Medium,
                        ToggleGroup = "mnt",
                        EnableToggle = true,
                        Listeners =
                        {
                            Toggle = { Handler = "if (this.pressed) { #{TM}.startTask('mnt'); }" }
                        }
                    }),
                    (cmdStop = new Button
                    {
                        ID = "cmdStop",
                        ToolTip = "Stop monitoring",
                        Cls = "x-btn-toggle",
                        IconCls = "icon-pause-24",
                        ToggleGroup = "mnt",
                        Flex = 1,
                        Scale = ButtonScale.Medium,
                        EnableToggle = true,
                        Pressed = true,
                        Listeners = { Toggle = { Handler = "if (this.pressed) { #{TM}.stopTask('mnt'); }" } }
                    }),
                }
            };

            Items.AddRange(new Component[]
            {
                new Container
                {
                    Layout = "HBox",
                    Flex = 1,
                    Margins = "1px 0 0 0",
                    Items =
                    {
                        (cntMain = new Container
                        {
                            Width = 106,
                            Height = 72,
                            Layout = "Fit",
                            Items = { cmdMain ,}
                        }),
                        new VBox
                        {
                            Stretch=true,
                            Items={
                                ctrlBar,
                                (ErrorLink = new Label
                                {
                                    ID = "ErrorLink",
                                    Text = "no errors...",
                                    ToolTip = "Monitoring errors",
                                    Width = 100,
                                    Height = 20,
                                    Margins = "0 0 0 10px",
                                }),
                            }
                        }
                    }
                },
            });


            Controls.Add(TM = new TaskManager
            {
                ID = "TM",
                Tasks =
                {
                    new Task {TaskID = "mnt", Interval = 30000, AutoRun = false},
                }
            });
        }

        public class ErrorType
        {
            public string Name { get; set; }
            public string Description { get; set; }
        }

        public int DefaultInterval { get; set; }
        public readonly List<ErrorType> ErrorTypes = new List<ErrorType>();

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            CreateChildControls();

            if (DefaultInterval > 0)
            {
                var c = FindControl("miRI" + DefaultInterval) as CheckMenuItem;
                if (c != null) c.Checked = true;
            }
        }


        public ErrorType AddErrorType(string name, string desc)
        {
            var o = new ErrorType { Name = name, Description = desc };
            ErrorTypes.Add(o);
            return o;
        }

        //Random rnd = new Random();
        public void AddState(int[] errorCounts)
        {
            if (errorCounts == null) return;
            CreateChildControls();
            StartModify();

            var errorCount = errorCounts.Sum(a => a);// +rnd.Next(100);

            if (errorCount > 0)
            {
                Cls = "x-composite-btn1-error";
                ErrorLink.Text = errorCount + " errors";
                ErrorLink.IconCls = "icon-error-16";
            }
            else
            {
                Cls = "x-composite-btn1";
                ErrorLink.Text = "no errors...";
                ErrorLink.Icon = Icon.None;
            }
        }

        public void AdaptTo(Panel tab)
        {
            CreateChildControls();

            tab.Listeners.Deactivate.Handler += " if (#{cmdRun}.pressed) #{cmdStop}.toggle(true);";
        }

        public void Adapt(IGridContainer gc)
        {
            CreateChildControls();

            var refreshScript = GridEquiper.GetRefreshScript(gc);
            TM.Tasks[0].Listeners.Update.Handler = cmdRefresh.OnClientClick =
                "var lm = " + gc.Grid.ClientID + ".loadMask;if(lm)lm.el=" + cntMain.ClientID + ".el;" +
                refreshScript;

            gc.Owner.Get<IStoreContainer>().Store.BaseParams["monitorId"] = ClientID;

            var ilogic = gc.Owner.Get<IListLogicContainer>();
            if (ilogic != null)
            {
                var logic = ilogic.Logic;
                Title = logic.EntityDesc.Names;
            }
        }


    }

}